package org.linlinjava.litemall.wx.service;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.linlinjava.litemall.core.config.WxProperties;
import org.linlinjava.litemall.core.util.RedisUntil;
import org.linlinjava.litemall.db.domain.SysWxConfig;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.service.SystemWxConfigService;
import org.linlinjava.litemall.wx.exception.ControllerException;
import org.linlinjava.litemall.wx.util.AesCbcUtil;
import org.linlinjava.litemall.wx.util.GlobalValue;
import org.linlinjava.litemall.wx.vo.wechart.returns.Code2SessionReturn;
import org.linlinjava.litemall.wx.vo.wechart.returns.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


import lombok.extern.log4j.Log4j;


@Service
@DependsOn(value = "GlobalValue")
public class WxService {
	private final Log log = LogFactory.getLog(WxService.class);
	@Autowired
	private RedisUntil redisService;
	@Autowired
	private SystemWxConfigService isysConfigDao;
	@Autowired
	private LitemallUserService consumerDao;

    public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";


	/*public String refreshToken() {
		String Access_token = redisService.get("AccessToken").toString();
    	if( StringUtils.isNotBlank(Access_token)) {
    		return Access_token;
    	}else {
			String grant_type = "client_credential";
			String AppId = GlobalValue.wxSubAppId;
			String secret = GlobalValue.wxSecret;
			String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grant_type + "&appid=" + AppId + "&secret="
					+ secret;
			log.info("url is : " + url);
			MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded; charset=UTF-8");
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(type);
			headers.add("Accept", MediaType.APPLICATION_JSON.toString());
			try {
				HttpEntity<String> formEntity = new HttpEntity<String>(headers);
				ResponseEntity<?> responseEntity = restTemplate.exchange(url, HttpMethod.GET, formEntity, String.class);

				if (200 == responseEntity.getStatusCodeValue()) {
					log.info("refresh accesstoken ok");
					log.info(responseEntity.getBody().toString());
					AccessToken actoken = JSON.parseObject(responseEntity.getBody().toString(), AccessToken.class);
					redisService.set("AccessToken", actoken.getAccess_token(), 115);
					return  actoken.getAccess_token();
				} else {
					log.error("get accesstoken error!!!");
					log.error(responseEntity.getStatusCodeValue());
					log.error(responseEntity.getBody());
					return null;
				}
			} catch (Exception e) {
				log.error(e.getMessage());
				return null;
			}
    	}
	}*/



	/**
     *	 获取Access_token
     * @return
     *@author caiy
     *	2019/4/18
     */

	public  String getAccess_token(String AppID,String sercret) {
    	String Access_token ="";
		if(redisService.get("accessToken")!=null) {
			Access_token = redisService.get("accessToken").toString();
		}else {
			Access_token =this.getWxAccess_token(AppID,sercret);
		}
		return Access_token;
	}


	private String getWxAccess_token(String AppID,String sercret) {
		String Access_token ="";
		//String AppId = GlobalValue.wxSubAppId;
		//String secret = GlobalValue.wxSecret;
		String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid="+AppID+"&secret="
				+ sercret;
		try {
			URL urlGet = new URL(url1);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes, "UTF-8");
			JSONObject demoJson = JSON.parseObject(message);
			Access_token = demoJson.getString("access_token");
			is.close();
		}catch (Exception e){
			log.error("获取access_token发生异常",e);
		}
		log.info("accessToken:"+Access_token);
		redisService.set("accessToken", Access_token, 110);
		return Access_token;
	}
	

	   /* public void  getAccessToken( String openid) {
	    	String access_token = this.getWxAccess_token();
	        String requestUrl = GetPageAccessTokenUrl.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
	        HttpClient client = null;
	        SysConsumer consumer = consumerDao.findByUserId(openid);
	        try {
	        	  if(consumer!=null) {
	        		  SysConsumer consumerNew = new SysConsumer();
	            client = new DefaultHttpClient();
	            HttpGet httpget = new HttpGet(requestUrl);
	            ResponseHandler<String> responseHandler = new BasicResponseHandler();
	            String response = client.execute(httpget, responseHandler);
	            JSONObject OpenidJSONO = JSONObject.parseObject(response);
//	            String accessToken = String.valueOf(OpenidJSONO.get("access_token"));
	            String subscribe = String.valueOf(OpenidJSONO.get("subscribe"));
	            String nickname = new String(String.valueOf(OpenidJSONO.get("nickname")).getBytes("ISO8859-1"),"UTF-8");
	            String sex = String.valueOf(OpenidJSONO.get("sex"));
	            String language = String.valueOf(OpenidJSONO.get("language"));
	            String city = new String(String.valueOf(OpenidJSONO.get("city")).getBytes("ISO8859-1"),"UTF-8");
	            String province = new String(String.valueOf(OpenidJSONO.get("province")).getBytes("ISO8859-1"),"UTF-8");
	            String country = new String(String.valueOf(OpenidJSONO.get("country")).getBytes("ISO8859-1"),"UTF-8");
	            String headimgurl = String.valueOf(OpenidJSONO.get("headimgurl"));
	            String subscribeTime = String.valueOf(OpenidJSONO.get("subscribe_time"));
	            String unionid = String.valueOf(OpenidJSONO.get("unionid"));
	            consumer.setNickName(nickname);
	            consumer.setGender(sex);
	            consumer.setProvince(province);
	            consumer.setCity(city);
	            consumer.setCountry(country);
	            consumer.setAvatarUrl(headimgurl);
	            consumer.setUpdatetime(new Date().getTime());
	            consumerDao.save(consumer);
	        }
	            
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            client.getConnectionManager().shutdown();
	        }
	    }*/
     public  String getAccess_token38(String apletname) {

       String Access_token ="";
       if(redisService.get("accessToken38")!=null) {
         Access_token = redisService.get("accessToken38").toString();
       }else {
         Access_token =this.getWxAccess_token38(apletname);
       }
       return Access_token;
     }
  private String getWxAccess_token38(String appletname) {
	  
    SysWxConfig wxConfig = isysConfigDao.getconfigByAppletNam(appletname);

    String Access_token ="";
    String AppId = wxConfig.getWxSubappid();
    String secret = wxConfig.getWxSecret();
    String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid="+AppId+"&secret="
      + secret;
    try {
      URL urlGet = new URL(url1);
      HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
      http.setRequestMethod("GET"); // 必须是get方式请求
      http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      http.setDoOutput(true);
      http.setDoInput(true);
      System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
      System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
      http.connect();
      InputStream is = http.getInputStream();
      int size = is.available();
      byte[] jsonBytes = new byte[size];
      is.read(jsonBytes);
      String message = new String(jsonBytes, "UTF-8");
      JSONObject demoJson = JSON.parseObject(message);
      Access_token = demoJson.getString("access_token");
      is.close();
    }catch (Exception e){
      log.error("获取access_token发生异常",e);
    }
    log.info("accessToken:"+Access_token);
    redisService.set("accessToken38", Access_token, 110);
    return Access_token;
  }

}
